define(function (require, exports, module) {
    return function (jQuery) {
        (function ($) {
            /*seajs-content-start*/
            var _4gCellResideCtrl = function ($scope, httpservice) {
                var dateFormat = function (date, fmt) { //author: meizz
                    var o = {
                        "M+": date.getMonth() + 1,                 //月份
                        "d+": date.getDate(),                    //日
                        "h+": date.getHours(),                   //小时
                        "m+": date.getMinutes(),                 //分
                        "s+": date.getSeconds(),                 //秒
                        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                        "S": date.getMilliseconds()             //毫秒
                    };
                    if (/(y+)/.test(fmt))
                        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                        if (new RegExp("(" + k + ")").test(fmt))
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                };

                var downloadoperate = function(cellvalue, options, rowObject){
                    var listprint = "<a class='viewmodel' href='javascript:'id='"+rowObject.id+"' title = '查看'><img src='../../../images/chakan.png' /></a>" +
                        "<a class='downloadmodel' style='margin: 0 15px;' href= '"+httpservice.downloadurl+""+rowObject.filename+".csv' target='_blank' id='"+rowObject.id+"' state='"+rowObject.status+"' title='下载'><img src='../../../images/download.png' /></a>" +
                        "<a class='deletemodel' href='javascript:' id='"+rowObject.id+"' state='"+rowObject.state+"' title='删除'><img src='../../../images/delete1.png' /></a>";
                    return listprint;
                };

                //提交下载任务
                var submitDownloadTask = function (postdata,posturl) {
                    $.ajax({
                        url: posturl,
                        type: "POST",
                        data: JSON.stringify(postdata),
                        dataType: "json",
                        success: function (result, textStatus) {
                            if(result.state){
                                alert('提交下载任务成功!');
                            }
                            else{
                                alert("提交下载任务失败,\r\n"+result.error);
                            }
                        },
                        error:function(xmlHttpRequest,textStatus){
                            alert("请求出错!");
                        },
                        complete:function(xmlHttpRequest,textStatus){

                        }
                    });
                };

                $scope.dayTime = dateFormat(new Date(new Date().setDate(new Date().getDate() - 1)),'yyyy-MM-dd');
                $scope.monthTime = dateFormat(new Date(new Date().setMonth(new Date().getMonth()-1)),'yyyy-MM');
                //每页记录数，10，20，50
                $scope.pageSize = 10;

                $scope.echart1 = {
                    chartdata:{
                        tooltip : {
                            formatter: "全网4g驻留比 : {c}%"
                        },
//                        toolbox: {
//                            show : true,
//                            feature : {
//                                mark : {show: true},
//                                restore : {show: true},
//                                saveAsImage : {show: true}
//                            }
//                        },
                        series : [
                            {
                                name:'',
                                type:'gauge',
                                detail : {
                                    formatter:'{value}%',
                                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                                        color: 'auto',
                                        fontWeight: 'normal',
                                        fontSize:20
                                    }},
                                min:0,
                                max:100,
                                data:[{value: 66, name: '全网4g驻留比'}],
                                radius: '90%',
                                axisLine: {            // 坐标轴线
                                    lineStyle: {       // 属性lineStyle控制线条样式
                                        color: [[0.2, '#2EC7C9'],[0.8, '#59B0EE'],[1, '#D8787F']],
                                        width: 5
                                    }
                                },
                                axisTick: {            // 坐标轴小标记
                                    splitNumber: 10,   // 每份split细分多少段
                                    length :8,        // 属性length控制线长
                                    lineStyle: {       // 属性lineStyle控制线条样式
                                        color: 'auto'
                                    }
                                },
                                splitLine: {           // 分隔线
                                    show: true,        // 默认显示，属性show控制显示与否
                                    length :12,         // 属性length控制线长
                                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                                        color: 'auto'
                                    }
                                },
                                pointer : {
                                    width : 5
                                }
                            }
                        ]
                    },
                    obj:{}
                };

                $scope.echart2 = {
                    chartdata:{
                        tooltip : {
                            formatter: "全网4g驻留比 : {c}%"
                        },
//                        toolbox: {
//                            show : true,
//                            feature : {
//                                mark : {show: true},
//                                restore : {show: true},
//                                saveAsImage : {show: true}
//                            }
//                        },
                        series : [
                            {
                                name:'',
                                type:'gauge',
                                detail : {
                                    formatter:'{value}%',
                                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                                        color: 'auto',
                                        fontWeight: 'normal',
                                        fontSize:20
                                    }},
                                min:0,
                                max:100,
                                data:[{value: 50, name: '全网4g驻留比'}],
                                radius: '90%',
                                axisLine: {            // 坐标轴线
                                    lineStyle: {       // 属性lineStyle控制线条样式
                                        color: [[0.2, '#2EC7C9'],[0.8, '#59B0EE'],[1, '#D8787F']],
                                        width: 5
                                    }
                                },
                                axisTick: {            // 坐标轴小标记
                                    splitNumber: 10,   // 每份split细分多少段
                                    length :8,        // 属性length控制线长
                                    lineStyle: {       // 属性lineStyle控制线条样式
                                        color: 'auto'
                                    }
                                },
                                splitLine: {           // 分隔线
                                    show: true,        // 默认显示，属性show控制显示与否
                                    length :12,         // 属性length控制线长
                                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                                        color: 'auto'
                                    }
                                },
                                pointer : {
                                    width : 5
                                }
                            }
                        ]
                    },
                    obj:{}
                };

                $scope.grid1 = {
                    gridpagedata:{
                        nowpage:1,
                        totalpage:20,
                        totalcount:20,
                        startline:1,
                        endline:20,
                        pagesize:$scope.pageSize,
                        pagelist:[10,20,50],
                        datacount:20,
                        toFirstpage: function(){
                            //首页
                            $scope.grid1.gridpagedata.nowpage = 1;
                            var condition ={
                                pageindex:$scope.grid1.gridpagedata.nowpage,
                                pagesize:$scope.grid1.gridpagedata.pagesize,
                                timesize:'day',
                                starttime:$scope.dayTime
                            }
                            $scope.turnPage(condition);
                        },
                        toToppage: function(){
                            //上一页
                            if ($scope.grid1.gridpagedata.nowpage > 1) {
                                $scope.grid1.gridpagedata.nowpage--;
                                var condition ={
                                    pageindex:$scope.grid1.gridpagedata.nowpage,
                                    pagesize:$scope.grid1.gridpagedata.pagesize,
                                    timesize:'day',
                                    starttime:$scope.dayTime
                                }
                                $scope.turnPage(condition);
                            }
                        },
                        toNextpage: function(){
                            //下一页
                            if ($scope.grid1.gridpagedata.nowpage < $scope.grid1.gridpagedata.totalpage) {
                                $scope.grid1.gridpagedata.nowpage++;
                                var condition ={
                                    pageindex:$scope.grid1.gridpagedata.nowpage,
                                    pagesize:$scope.grid1.gridpagedata.pagesize,
                                    timesize:'day',
                                    starttime:$scope.dayTime
                                }
                                $scope.turnPage(condition);
                            }
                        },
                        toLastpage: function(){
                            //最后一页
                            $scope.grid1.gridpagedata.nowpage = $scope.grid1.gridpagedata.totalpage;
                            var condition ={
                                pageindex:$scope.grid1.gridpagedata.nowpage,
                                pagesize:$scope.grid1.gridpagedata.pagesize,
                                timesize:'day',
                                starttime:$scope.dayTime
                            }
                            $scope.turnPage(condition);
                        },
                        topage: function(){
                            //alert('第' + $scope.grid1.gridpagedata.nowpage + '页');
                            var condition ={
                                pageindex:$scope.grid1.gridpagedata.nowpage,
                                pagesize:$scope.grid1.gridpagedata.pagesize,
                                timesize:'day',
                                starttime:$scope.dayTime
                            }
                            $scope.turnPage(condition);
                        },
                        changePagesize: function(){
                            //alert('切换到每页' + $scope.grid1.gridpagedata.pagesize + '条');
                            $scope.grid1.gridpagedata.nowpage = 1;
                            var condition ={
                                pageindex:$scope.grid1.gridpagedata.nowpage,
                                pagesize:$scope.grid1.gridpagedata.pagesize,
                                timesize:'day',
                                starttime:$scope.dayTime
                            }
                            $scope.turnPage(condition);
                        }
                    },
                    griddata: {
                        colnames: ['日期','站点', '4G流量驻留比'],
                        colmodel: [
                            { name: 'datetime', index: 'datetime', align:"center" },
                            { name: 'cellname', index: 'cellname', align:"center" },
                            { name: '_4gpct', index: '_4gpct', align:"center"}
                        ],
                        data: [
//                            { datetime: "2016-12-12", cell:78834, _4gresidepct:"70%" },
//                            { datetime: "2016-12-12", cell:78835, _4gresidepct:"75%" },
//                            { datetime: "2016-12-12", cell:78836, _4gresidepct:"80%" },
//                            { datetime: "2016-12-12", cell:78837, _4gresidepct:"60%" }
                        ]
                    },
                    obj:{},
                    shrinkToFit:true,
                    gridresize: function (grid) {
                        grid.setGridWidth($(window).width()*0.49);
                        grid.setGridHeight($(window).height()-375);
                    }
                };

                $scope.grid2 = {
                    gridpagedata:{
                        nowpage:1,
                        totalpage:20,
                        pagesize:$scope.pageSize,
                        pagelist:[10,20,50],
                        toFirstpage: function(){
                            //alert('首页');
                            $scope.grid2.gridpagedata.nowpage = 1;
                            var condition ={
                                pageindex:$scope.grid2.gridpagedata.nowpage,
                                pagesize:$scope.grid2.gridpagedata.pagesize,
                                timesize:'month',
                                starttime:$scope.monthTime
                            }
                            $scope.turnPage(condition);
                        },
                        toToppage: function(){
                            //alert('上一页');
                            if ($scope.grid2.gridpagedata.nowpage > 1) {
                                $scope.grid2.gridpagedata.nowpage--;
                                var condition ={
                                    pageindex:$scope.grid2.gridpagedata.nowpage,
                                    pagesize:$scope.grid2.gridpagedata.pagesize,
                                    timesize:'month',
                                    starttime:$scope.monthTime
                                }
                                $scope.turnPage(condition);
                            }
                        },
                        toNextpage: function(){
                            //alert('下一页');
                            if ($scope.grid2.gridpagedata.nowpage < $scope.grid2.gridpagedata.totalpage) {
                                $scope.grid2.gridpagedata.nowpage++;
                                var condition ={
                                    pageindex:$scope.grid2.gridpagedata.nowpage,
                                    pagesize:$scope.grid2.gridpagedata.pagesize,
                                    timesize:'month',
                                    starttime:$scope.monthTime
                                }
                                $scope.turnPage(condition);
                            }
                        },
                        toLastpage: function(){
                            //alert('最后一页');
                            $scope.grid2.gridpagedata.nowpage = $scope.grid2.gridpagedata.totalpage;
                            var condition ={
                                pageindex:$scope.grid2.gridpagedata.nowpage,
                                pagesize:$scope.grid2.gridpagedata.pagesize,
                                timesize:'month',
                                starttime:$scope.monthTime
                            }
                            $scope.turnPage(condition);
                        },
                        topage: function(){
                            //alert('第' + $scope.grid1.gridpagedata.nowpage + '页');
                            var condition ={
                                pageindex:$scope.grid2.gridpagedata.nowpage,
                                pagesize:$scope.grid2.gridpagedata.pagesize,
                                timesize:'month',
                                starttime:$scope.monthTime
                            }
                            $scope.turnPage(condition);
                        },
                        changePagesize: function(){
                            //alert('切换到每页' + $scope.grid1.gridpagedata.pagesize + '条');
                            $scope.grid2.gridpagedata.nowpage = 1;
                            var condition ={
                                pageindex:$scope.grid2.gridpagedata.nowpage,
                                pagesize:$scope.grid2.gridpagedata.pagesize,
                                timesize:'month',
                                starttime:$scope.monthTime
                            }
                            $scope.turnPage(condition);
                        }
                    },
                    griddata: {
                        colnames: ['日期','站点', '4G流量驻留比'],
                        colmodel: [
                            { name: 'datetime', index: 'datetime', align:"center" },
                            { name: 'cellname', index: 'cellname', align:"center" },
                            { name: '_4gpct', index: '_4gpct', align:"center"}
                        ],
                        data: [
//                            { datetime: "2016-11", cell:78834, _4gresidepct:"70%" },
//                            { datetime: "2016-11", cell:78835, _4gresidepct:"75%" },
//                            { datetime: "2016-11", cell:78836, _4gresidepct:"60%" },
//                            { datetime: "2016-11", cell:78837, _4gresidepct:"55%" }
                        ]
                    },
                    obj:{},
                    shrinkToFit:true,
                    gridresize: function (grid) {
                        grid.setGridWidth($(window).width()*0.49);
                        grid.setGridHeight($(window).height()-375);
                    }
                };

                $scope.turnPage = function(condition){
                    $scope.$emit('loading', 'true');
                    var f = $scope.getGridData(condition);
                    $.when(f).then(function(){

                    }).always(function() {
                            $scope.$emit('loading', 'false');
                            $scope.$apply();
                        });
                }

                $scope.flushPage = function(condition) {
                    $scope.$emit('loading', 'true');
                    var f1 = $scope.getEChartData(condition);
                    var f2 = $scope.getGridData(condition);
                    $.when(f1,f2).then(function(){

                    }).always(function() {
                            $scope.$emit('loading', 'false');
                            $scope.$apply();
                        });
                }

                document.initWdatePicker = function(timesize){
                    WdatePicker(
                        {
                            skin:'twoer',
                            dateFmt:timesize=='day'?'yyyy-MM-dd':'yyyy-MM',
                            onpicking:function(dp){
                                if(timesize == 'day'){
                                    $scope.dayTime = dp.cal.getNewDateStr();
                                    $scope.grid1.gridpagedata.nowpage = 1;
                                }
                                else{
                                    $scope.monthTime = dp.cal.getNewDateStr();
                                    $scope.grid2.gridpagedata.nowpage = 1;
                                }
                                var condition ={
                                    pageindex:timesize=='day'?$scope.grid1.gridpagedata.nowpage:$scope.grid2.gridpagedata.nowpage,
                                    pagesize:timesize=='day'?$scope.grid1.gridpagedata.pagesize:$scope.grid2.gridpagedata.pagesize,
                                    timesize:timesize,
                                    starttime:dp.cal.getNewDateStr()
                                }
                                $scope.flushPage(condition);
                            }
                        }
                    );
                }

                //查询天粒度全网4g驻留比(仪表盘)
                $scope.getEChartData = function(condition){
                    return httpservice.post("script/_4gCellReside/GetAllNet4GResideRate",JSON.stringify(condition),function(result){
                        if (result._4g_pct == null) {
                            if(condition.timesize == 'day'){

                                $scope.echart1.chartdata.series[0].data[0].value = 0;

                            }
                            else{
                                $scope.echart2.chartdata.series[0].data[0].value = 0;
                            }
                        }
                        else {
                            if(condition.timesize == 'day'){

                                $scope.echart1.chartdata.series[0].data[0].value = result._4g_pct;

                            }
                            else{
                                $scope.echart2.chartdata.series[0].data[0].value = result._4g_pct;
                            }
                        }
                        $scope.$apply();
                    });
                }

                $scope.getGridData = function(condition){
                    return httpservice.post("script/_4gCellReside/Get4GCellResideRate",JSON.stringify(condition),function(result){
                        if(condition.timesize == 'day'){
                            $scope.grid1.gridpagedata.totalcount = result.recordCount;
                            $scope.grid1.gridpagedata.totalpage = result.pageCount;
                            $scope.grid1.gridpagedata.startline = result.startLine;
                            $scope.grid1.gridpagedata.endline = result.endLine;
                            $scope.grid1.gridpagedata.datacount = result.dataCount;
                            $scope.grid1.griddata.data = result.datas;
                        }
                        else{
                            $scope.grid2.gridpagedata.totalcount = result.recordCount;
                            $scope.grid2.gridpagedata.totalpage = result.pageCount;
                            $scope.grid2.gridpagedata.startline = result.startLine;
                            $scope.grid2.gridpagedata.endline = result.endLine;
                            $scope.grid2.gridpagedata.datacount = result.dataCount;
                            $scope.grid2.griddata.data = result.datas;
                        }
                        $scope.$apply();
                    });
                }

                $scope.dialogList={
                    title:"下载列表",
                    ok:function(){},
                    cancel:function(){}
                }

                $scope.downloadList = {
                    griddata: {
                        colnames: ['ID','下载文件名', '创建时间','主模块','子模块','应用名称', '下载状态', '操作'],
                        colmodel: [
                            { name: 'id', index: 'id', sortable: false, align:"center",hidden:true },
                            { name: 'filename', index: 'filename', sortable: false, align:"center" },
                            { name: 'createtime', index: 'createtime', sortable: false, align:"center" },
                            { name: 'mainmodule', index: 'mainmodule', sortable: false, align:"center"},
                            { name: 'submodule', index: 'submodule', sortable: false, align:"center"},
                            { name: 'appname', index: 'appname', sortable: false,sorttype: 'number', align:"center"},
                            { name: 'status', index: 'status', sortable: false,sorttype: 'number', align:"center"},
                            { name: 'operate', index: 'operate', sortable: false, align:"center",formatter:downloadoperate}
                        ],
                        data: [
                            { "filename": "微信", "mainmodule": 1000, "submodule":1000, "appname":1000, "createtime": 1000,"status":1000, "operate":1000}
                        ]
                    },
                    obj:{},
                    shrinkToFit:true,
                    gridresize: function (grid) {
                        grid.setGridWidth(800);
                        grid.setGridHeight(300);
                    }
                };

                $scope.showDownloadlist = function(){
                    $scope.dialogList.show();
                    $scope.getCheckDownloadList();
                }

                $scope.getDownloadList = function(postdata){
                    $.ajax({
                        url:httpservice.serverurl + "script/Common/GetTaskList",
                        type:"post",
                        data:JSON.stringify(postdata),
                        dataType:"json",
                        success:function(result){
                            $scope.downloadList.griddata.data = result.datas;
                            $scope.$apply();
                        },
                        error:function(xmlHttpRequest,textStatus){
                            //alert("请求出错!");
                        },
                        complete:function(xmlhHttpRequest,textStatus){

                        }
                    });
                }

                $scope.getCheckDownloadList = function(){
                    var condition = {
                        mainmodule:"网络指标监控",
                        submodule:"4G流量驻留比"
                    }
                    $scope.getDownloadList(condition);
                }

                //
                $scope.submitTask = function(size){
                    var isData = true;
                    switch(size){
                        case 'day':
                            isData = ($scope.grid1.griddata.data.length>0);
                            break;
                        case 'month':
                            isData = ($scope.grid2.griddata.data.length>0);
                            break;
                    }
                    if(!isData){
                        alert('无数据导出，请先查询!');
                        return false;
                    }
                    var condition ={
                        starttime:size=="day"?$scope.dayTime:$scope.monthTime,
                        timesize:size,
                        mainmodule:"网络指标监控",
                        submodule:"4G流量驻留比",
                        appname:'4G流量驻留比'
                    }
                    var url = httpservice.serverurl + "script/_4gCellReside/Submit4GCellResideRateTask";
                    submitDownloadTask(condition,url);
                }

                //删除下载文件
                $(".deletemodel").live("click",function(e){
                    var fileId = $(e.target).parent().attr("id");
                    if(confirm('你确定要删除该文件?')){
                        $.ajax({
                            url:httpservice.serverurl + "script/Common/DeleteTask",
                            type:"get",
                            data:{id:fileId},
                            dataType:"json",
                            success:function(result){
                                if(result.state){
                                    var condition = {
                                        mainmodule:"网络指标监控",
                                        submodule:"4G流量驻留比"
                                    }
                                    $scope.getDownloadList(condition);
                                    alert('删除成功!');
                                }
                                else{
                                    alert('删除失败!');
                                }
                            },
                            error:function(xmlHttpRequest,textStatus){
                                alert('请求出错!');
                            },
                            complete:function(xmlHttpRequest,textStatus){

                            }
                        });
                    }
                })

                $scope.init = function(){
                    //日粒度图表显示
                    var condition ={
                        pageindex:1,
                        pagesize:$scope.pageSize,
                        timesize:'day',
                        starttime:$scope.dayTime
                    }
                    $scope.flushPage(condition);

                    //月粒度图表显示
                    var condition ={
                        pageindex:1,
                        pagesize:$scope.pageSize,
                        timesize:'month',
                        starttime:$scope.monthTime
                    }
                    $scope.flushPage(condition);

                    $scope.getCheckDownloadList();
                    setInterval(function(){
                        $scope.$apply($scope.getCheckDownloadList);
                    }, 60*1000);
                };

                $scope.init();
            };
            angular.module('_4gCellReside-ctrl', [])
                .controller('_4gCellResideCtrl', ['$scope', 'HttpService', _4gCellResideCtrl]);
            /*seajs-content-end*/
        })(jQuery);
    }
});